package com.test.json;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * 
 *
 * @author Richard - rui.wu@bitmain.com
 * @since 2016年7月27日 
 *
 */
public class JsonDemo {
	public static void main(String[] args) {
		Socket socket = null;
		BufferedWriter writer = null;
		BufferedReader reader = null;
		StringBuilder result = null;
		
		String host = "192.168.20.60";
		int port = 4028;
		
		try {
			socket = new Socket();
			socket.setSoTimeout(60000);
			socket.connect(new InetSocketAddress(host,port));
			
			writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			writer.write("{\"command\":\"stats\"}");
			writer.flush();
			
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			
			result = new StringBuilder();
			String str;
			while((str=reader.readLine())!=null){
				result.append(str);
			}
			
			String rs = result.toString().trim();
			System.out.println(rs);
			
			JsonParser parser = new JsonParser();
			JsonElement element = parser.parse(rs).getAsJsonObject().get("STATS");
			JsonArray array = element.getAsJsonArray();
			JsonObject stats = array.get(0).getAsJsonObject();
			String compileTime = stats.get("CompileTime").getAsString();
			System.out.println("CompileTime:"+compileTime);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(writer!=null){
					writer.close();
					writer = null;
				}
				if(reader!=null){
					reader.close();
					reader = null;
				}
				if(socket!=null){
					socket.close();
					socket = null;
				}
			} catch (Exception e2) {
			}
		}
	}
}
